<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>收货计划管理</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
	<style type="text/css">
		.tmdyTable td{border:1px solid #00000080;} 
		.laytable-cell-1-imageUrl{
			height:100%;
			max-width:100%;
		}
	</style>
</head>
<script type="text/javascript">
	$(document).on('keydown','[lay-id="productAddTable"] .layui-table-edit',function(e){
		var td = $(this).parent('td'),
		tr = td.parent('tr'),
		trs = tr.parent().parent().find('tr'),
		tr_index = tr.index(),
		td_index = td.index(),
		td_last_index = tr.find('[data-edit="text"]:last').index(),
		td_first_index = tr.find('[data-edit="text"]:first').index();
		switch(e.keyCode){
			case 13:
			case 39:
				td.nextAll('[data-edit="text"]:first').click();
				if(td_index == td_last_index){
					tr.next().find('td').eq(td_first_index).click();
					if(tr_index == trs.length-1){
						trs.eq(0).find('td').eq(td_first_index).click();
					}
				}
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
			case 37:
				td.prevAll('[data-edit="text"]:first').click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
			case 38:
				tr.prev().find('td').eq(td_index).click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
			case 40:
				tr.next().find('td').eq(td_index).click();
				setTimeout(function(){
					$('.layui-table-edit').select()
				},0)
			break;
		} 
	})
</script>
<body class="layui-anim layui-anim-up">
<div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>收货计划管理</cite>
        </a>
      </span>
</div>
<div class="x-body">
	<div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<!-- 获取收货单号 -->
						<input id="getReceiveNumberValue" hidden="hidden">
						<input id="gys" hidden="hidden">
						<input id="getIndex" hidden="hidden">
						<input class="layui-input" name="sendNumber" id="sendNumberc" placeholder="请输入送货单号" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
					</td>
					<td>
					 <input class="layui-input" readonly name="sendCompany" id="sendCompanyc1" value="${cname}"autocomplete="off" style="display: inline; width: 180px; margin-left: 10px"> 
						 <input class="layui-input" name="sendCompany" id="sendCompanyc" value="${cid}" type="hidden">
					</td>

					<td>

						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select id="selectState" name="selectState">
								<option value="">请选择收货状态</option>
								<option value="1">已收货</option>
								<option value="0">未收货</option>
							</select>
						</div>
					</td>
					<td>
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select id="selectType" name="selectType">
								<option value="">请选择类型</option>
								<option value="0">正常入库</option>
								<option value="1">发货退回</option>
							</select>
						</div>
					</td>
					 <td>
						<div class="layui-form" style="width: 180px; margin-left: 10px">
							<select id="selectFlag" name="selectFlag">
								<option value="">请选择取消状态</option>
								<option value="0">已取消</option>
								<option value="1">已恢复</option>
								<option value="2">未操作</option>
							</select>
						</div>
					</td>
					<td class="layui-input-inline">
						<input class="layui-input" id="startTime" placeholder="请输入开始时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						-<input class="layui-input" id="endTime" placeholder="请输入结束时间" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px"> 
					</td>
				</tr>
			</table>
		</div>
		<button class="layui-btn layui-btn-normal" data-type="reload1"><i class="layui-icon layui-icon-search"></i>检索</button>
	</div>
	<xblock>
		<button class="layui-btn layui-btn-warm" id="add"><i class="layui-icon layui-icon-add-circle-fine"></i>新增</button>
		<button class="layui-btn layui-btn-danger" id="dels"><i class="layui-icon layui-icon-delete"></i>批量取消</button>
		<button class="layui-btn layui-btn-danger" id="restors"><i class="layui-icon layui-icon-delete"></i>批量恢复</button>
		<button class="layui-btn layui-btn-danger" id="dybd"><i class="layui-icon layui-icon-upload-drag"></i>打印表单</button>
		<button class="layui-btn layui-btn-danger" id="dybq"><i class="layui-icon layui-icon-upload-drag"></i>打印标签</button>
		<button class="layui-btn layui-btn-danger" id="export"><i class="layui-icon layui-icon-upload"></i>导出</button>
		<button class="layui-btn layui-btn-warm" id="merge"><i class="layui-icon layui-icon-add-circle-fine"></i>单据合并</button>
	</xblock>
	<div id="subDiv2">
	<table class="layui-hide" id="tableList" lay-filter="tableList"></table>
	</div>
	<div id="subDiv1" hidden="hidden">
	<table class="layui-hide" id="tableList1" lay-filter="tableList1"></table>
	</div>
</div>
<div id="subDiv" hidden="hidden">
	<xblock>
		<button class="layui-btn layui-btn-warm" id="addProduct"><i class="layui-icon layui-icon-add-circle-fine"></i>新增物料</button>
		<button class="layui-btn layui-btn-danger" id="delete2"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
	</xblock>
	<table class="layui-hide" id="tableDetails" lay-filter="tableDetails"></table>
</div>

<script type="text/html" id="rowToolbar">
	{{#  if(d.state ==0){ }}
		<a class="layui-btn layui-btn-xs" lay-event="confirmor"><i class="layui-icon layui-icon-edit"></i>确认</a>
    {{#  } }}
</script>

<script type="text/html" id="rowToolbar2">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete1"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>

<script type="text/html" id="productAddRowToolbar">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="proDel">删除</a>
</script>

<!-- 导入框 -->
<div id="importDiv" hidden="hidden">
	<form class="layui-form" id="uploadform">
		<div style="margin: 20px 0 20px 140px;">
			<input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
		</div>
	</form>
	<button class="layui-btn layui-btn-blue" lay-filter="uplodeform" style="margin-left: 80px">导入数据</button>&emsp;&emsp;&emsp;&emsp;
	<button type="button" class="layui-btn" id="downloadFile">下载模板</button>
</div>
<!-- 产品选择框 -->
<div id="productDiv" hidden="hidden">
	<form class="layui-form">
		<div style="margin-bottom: 18px">
			<div class="layui-inline">
				<table style="margin-top: 10px">
					<tr>
						<!-- <td>
							<input class="layui-input" name="materiel_name" id="materiel_name" placeholder="请输入中文名称" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td> -->
						<td>
							<input class="layui-input" name="materiel_num" id="materiel_num" placeholder="请输入SAP/QAD" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td>
					</tr>
				</table>
			</div>
			&emsp;<button style="margin-top: 10px" class="layui-btn layui-btn-normal" type="button" id="selectMateriel" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
		</div>
		<table id="productTable" lay-filter="productTable"></table>
			<input id="dtim" type="hidden">
		<xblock>
			<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform" style="margin: 0px 0px 10px 200px; width: 500px">提交</button>
		</xblock>
	</form>
</div>

<!-- 二次产品选择框 -->
<div id="productDiv2" hidden="hidden">
	<form class="layui-form" id="addFormID2">
		<div style="margin-bottom: 18px">
			<div class="layui-inline">
				<table style="margin-top: 10px">
					<tr>
						<!-- 
						<td>
							<input class="layui-input" name="materiel_name" id="materiel_name2" placeholder="请输入中文名称" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
						</td> 
						-->
						<td>
							<input class="layui-input" name="materiel_num" id="materiel_num2" placeholder="请输入SAP/QAD" autocomplete="off" style="display: inline; width: 300px; margin-left: 10px">
						</td>
					</tr>
				</table>
			</div>
			&emsp;<button style="margin-top: 10px" class="layui-btn layui-btn-normal" type="button" id="selectMateriel2" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
		</div>
		<table id="productTable2" lay-filter="productTable2"></table>
		<xblock>
			<button class="layui-btn layui-btn-blue" lay-submit lay-filter="productform2" type="button" style="margin: 0px 0px 10px 500px; width: 400px;margin-left: 250px;">提交</button>
		</xblock>
	</form>
</div>

<!-- 新增框 -->
<div id="addDivID" hidden="hidden">
	<form class="layui-form" id="addFormID">
		<xblock>
			<table>
				<tr>
					<td><label class="layui-form-label">收货单号</label></td>
					<td>
						<input readonly class="layui-input" id="receiveNumber" name="receiveNumber" style="width: 160px; color: gray" placeholder="请输入收货单号">
						<input type="hidden" id="id" name="id">
					</td>
					<td>
						<label class="layui-form-label">供应商</label></td>
					<td>
				
					 <input class="layui-input" name="sen" id="sen" value="${cname}" autocomplete="off" style="display: inline; width: 160px; color: gray"> 
					 
						 	<input type="hidden" name="sendCompany" id="sendCompany1"  value="${cid}" >
						 <div class="layui-inline" style="margin-top: 10px;">
							<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
						</div>
					</td>
					<td>
						<label class="layui-form-label">发货人</label>
					</td>
					<td>
							<input readonly class="layui-input" id="sendName" name="sendName" value="${lname}"style="width: 160px; color: gray">
					</td>
				</tr>
				<tr style="height: 10px"></tr>
				<tr>
					<td>
						<label class="layui-form-label">发货日期</label>
                    </td>
					<td>
						<input class="layui-input" id="sendDate" name="sendDate" style="width: 160px" placeholder="请选择发货日期">
					</td>
					<td>
						<label class="layui-form-label">送货单号</label>
                    </td>
					<td>
						<div class="layui-input-inline" style="width:160px">
							<input class="layui-input" id="sendNumber" name="sendNumber" style="width: 160px" placeholder="请输入送货单号">
						</div>
						<div class="layui-inline" style="margin-top: 10px;">
							<span style="color:red; font-size: 24px; margin-left: 4px">*</span>
						</div>
					</td>
                    <td>
						<label class="layui-form-label">备注</label>
                    </td>
					<td>
						<input class="layui-input" id="remark" name="remark" style="width: 160px" placeholder="请输入备注">
					</td>
					</tr>
				
					<tr style="height: 10px"></tr>
					<tr>
					<td>
						<label class="layui-form-label">收货联系人</label>
					</td>
					<td>
						<input readonly class="layui-input" id="rName" name="rName" value="${charger}"style="width: 160px; color: gray">
					</td>
					<td>
						<label class="layui-form-label">收货人电话</label>
					</td>
					<td>
						<input readonly class="layui-input" id="rtel" name="rtel"   value="${chargertel}" style="width: 160px; color: gray">
					</td>
						<td>
							<label class="layui-form-label">类型</label></td>
						<td>
							<div class="layui-input-inline" style="width:160px">
								<select class="layui-input" name="type" id="type">
									<option value="0">正常入库</option>
									<option value="1">发货退回</option>
								</select>
							</div>
						</td>
					</tr>
					<tr style="height: 10px"></tr>
					<tr>
	                    <td>
	                        <label class="layui-form-label"></label>
	                    </td>
	                    <td>
	                        <button type="button" class="layui-btn layui-btn-normal" onclick="addProduct()">选择物料</button>
	                    </td>
					</tr>
					<!-- 
					<tr>
	                    <td>
	                        <label class="layui-form-label"></label>
	                    </td>
	                    <td>
	                        <button type="button" class="layui-btn layui-btn-normal" onclick="addProduct()">选择物料</button>
	                    </td>
					</tr> 
					-->
				<tr style="height:10px"></tr>
			</table>
		</xblock>
		<table id="productAddTable" lay-filter="productAddTable"></table>
		<xblock>
			<div align="center">
				<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm">提交</button>
				&emsp;&emsp;&emsp;&emsp;
				<button class="layui-btn layui-btn-primary">取消</button>
			</div>
		</xblock>
	</form>
</div>

<!-- 打印表单框 -->
<div id="dybdDivID" hidden="hidden">
	<div id="dyDiv" style="width: 100%;overflow-y:scroll;height: 549px">
		<table style="width: 100%;">
			<tr>
				<td align="center" rowspan="2">
					<img alt="" src="${pageContext.request.contextPath }/images/title.jpg">
				</td>
				<td align="center" colspan="2">
					<h1><span class="xt_title"></span></h1>
				</td>
			</tr>
			<tr>
				<td align="center" colspan="2">
					<h1>收货单</h1>
				</td>
			</tr>
			<tr style="height:3px"></tr>
			<tr>
				<td colspan="3" width="100%" align="center">
					<table width="70%">
						<tr>
							<td width="40%">
								送货单号：<span id="sendNumbers"></span>
							</td>
							<td width="30%">
								到货日期：
							</td>
							<td rowspan="7" width="30%">
								<img width="200px" id="bd_img"/>
							</td>
						</tr>
						<tr>
							<td>
								创建时间：<span id="createDate"></span>
							</td>
							<td>
								窗口时间：
							</td>
						</tr>
						<tr>
							<td>
								客户名称：<span id="sendNames"></span>
							</td>
							<td>
								到货地址：<span id="receiveAddress"></span>
							</td>
						</tr>
						<tr>
							<td>
								客户地址：<span id="sendAddress"></span>
							</td>
							<td>
								交货道口：
							</td>
						</tr>
						<tr>
							<td>
								发货联系人：<span id="sendPeoples"></span>
							</td>
							<td>
								收货联系人：<span id="receivePeoples"></span>
							</td>
						</tr>
						<tr>
							<td>
								联系电话：<span id="sendPhones"></span>
							</td>
							<td>
								联系电话：<span id="receivePhones"></span>
							</td>
						</tr>
						<tr>
							<td>
								备注：
							</td>
							<td>
								备注：
							</td>
						</tr>
					</table>
				</td>
			</tr>
			<tr style="height:5px"></tr>
			<tr>
				<td colspan="6"  width="100%" align="center">
					<table id="dytable" lay-filter="dytable">
					</table>
				</td>
			</tr>
			<tr style="height:5px"></tr>
			<tr>
				<td align="center">
					发货人签字：
				</td>
				<td>
					承运商签字：
				</td>
				<td>
					收货人签字：
				</td>
			</tr>
			<tr>
				<td align="center">
					时间：
				</td>
				<td>
					时间：
				</td>
				<td>
					时间：
				</td>
			</tr>
			<tr style="height:5px"></tr>
			<tr>
				<td colspan="3" style="font-size: 12px;color: red">
					1. 发货时务必填全发货零件信息。
				</td>
			</tr>
			<tr>
				<td colspan="3" style="font-size: 12px;color: red">
					2. 收货数量按实际数量核对签收。
				</td>
			</tr>
			<tr>
				<td colspan="3" style="font-size: 12px;color: red">
					3. 单据一式三联，发货、收货、收货回单。
				</td>
			</tr>
		</table>
	</div>
	<xblock>
		<div align="right" style="margin-bottom: 0px;">
			<button type="button" id="dayingTable" class="layui-btn" style="margin-left: 450px;background-color: #57575799;"><i class="layui-icon">&#xe66e;</i>打印</button>
		</div>
	</xblock>
</div>
<!-- 打印标签条码框 -->
<div id="dybqDivID" hidden="hidden">
	<div style="width: 100%;overflow-y:scroll;height: 499px">
		<table id="bqtable" lay-filter="bqtable">
		</table>
	</div>
	<xblock>
		<div align="right" style="margin-bottom: 0px;">
			<button type="button" id="dytm" class="layui-btn" style="margin-left: 450px;background-color: #57575799;"><i class="layui-icon">&#xe66e;</i>打印</button>
		</div>
	</xblock>
</div>
<!-- 打印标签框 -->
<div id="dytmDivID" hidden="hidden">
	<div id="tmdyDiv" style="width: 100%;overflow-y:scroll;height: 499px">
		<%-- <table class="tmdyTable" style="border: 2px solid #222;width: 540px;height: 260px;margin:0 auto;">
			<tr>
				<td width="100" align="center">
					零件名称：
				</td>
				<td width="200">
					<span id="materiel_name"></span>
				</td>
				<td rowspan="8">
					<img src="<%=request.getContextPath()%>/images/logo.png" width="100%" height="100%"/>
				</td>
			</tr>
			<tr>
				<td align="center">
					零件号：
				</td>
				<td>
					<span id="brevity_num"></span>
				</td>
			</tr>
			<tr>
				<td align="center">
					供应商：
				</td>
				<td>
					<span id="brevity_num"></span>
				</td>
			</tr>
			<tr>
				<td align="center">
					包装信息：
				</td>
				<td>
					<span id="packing_quantity"></span>
				</td>
			</tr>
			<tr>
				<td align="center">
					包装数量：
				</td>
				<td>
					<span id="packing_quantity"></span>
				</td>
			</tr>
			<tr>
				<td align="center">
					日期时间：
				</td>
				<td>
					<span id="time"></span>
				</td>
			</tr>
			<tr>
				<td align="center">
					批次信息：
				</td>
				<td>
					<span id="pici"></span>
				</td>
			</tr>
			<tr>
				<td align="center">
					条码信息：
				</td>
				<td>
					<span id="tm"></span>
				</td>
			</tr>
			<tr>
				<td colspan="3">
					<img src="<%=request.getContextPath()%>/images/logo.png" width="100%" height="100%" id="dpddremark_dy"/>
				</td>
			</tr>
			<tr style="height:5px"></tr>
		</table> --%>
	</div>
	<xblock>
		<div align="right" style="margin-bottom: 0px;">
			<button type="button" id="dayingTmdyTable" class="layui-btn" style="margin-left: 450px;background-color: #57575799;"><i class="layui-icon">&#xe66e;</i>打印</button>
		</div>
	</xblock>
</div>
<script type="text/javascript">
    var table;
    var customerId2;
    var receiveNumber2;
    layui.use(['table','layer','upload','form','laydate'], function(){
        table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var laydate = layui.laydate;

      //日期时间范围
    	var minListDate = "1000-01-01 00:00:00";//最小可选时间，例：1990-02-01
        var maxListDate = "3000-12-31 23:59:59";//最大可选时间，例：2200-12-31   
        var enddate = laydate.render({
            elem: "#endTime",
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime',
            min: minListDate,
            max: maxListDate,
            done: function (val, date) {
                if (date && date.year){
                	//设置结束时间 设置开始时间的最大值为结束时间
                    begindate.config.max = {
                        year: date.year,
                        month: date.month - 1,//必须减1才是正确值
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: date.seconds
                    };
                }else {
                	//清除结束值    设置开始时间最大值
                    var dateInit = new Date(maxListDate.replace(/-/g, "/"));
                    begindate.config.max = {
                        year: dateInit.getFullYear(),
                        month: dateInit.getMonth(),
                        date: dateInit.getDate(),
                        hours: dateInit.getHours(),
                        minutes: dateInit.getMinutes(),
                        seconds: dateInit.getSeconds()
                    };
                }
            }
        });
        var begindate = laydate.render({
            elem: "#startTime",
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime',
            min: minListDate,
            max: maxListDate,
            done: function (val, date) {
                if (date && date.year){
                	//设置开始时间 设置结束时间的最小值为开始时间
                    enddate.config.min = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: date.seconds
                    };
                }else {
                	//清除开始值 ，设置结束值最小值
                    var dateInit = new Date(minListDate.replace(/-/g, "/"));
                    enddate.config.min = {
                        year: dateInit.getFullYear(),
                        month: dateInit.getMonth(),
                        date: dateInit.getDate(),
                        hours: dateInit.getHours(),
                        minutes: dateInit.getMinutes(),
                        seconds: dateInit.getSeconds()
                    };
                }
            }
        });
        
        
        var $ = layui.jquery, active = {
            reload1:function () {
            	var sendNumber = $.trim($("#sendNumberc").val());
                var sendCompany = $.trim($("#sendCompanyc").val());
                var selectState = $.trim($("#selectState").val());
                var selectFlag=$('#selectFlag').val();
                var startEndTimeWhere = "";
                var startTime = $.trim($("#startTime").val());
              /*   if(selectState==''){
                	
                	selectState=0;
                } */
				if(startTime != null && startTime != ""){
					startEndTimeWhere = startEndTimeWhere + " and send_date >= '"+startTime+"' ";
				}
				var endTime = $.trim($("#endTime").val());
				if(endTime != null && endTime != ""){
					startEndTimeWhere = startEndTimeWhere + " and send_date <= '"+endTime+"' ";
				}
				var selectType = $.trim($("#selectType").val());
				if(selectType != null && selectType != ""){
					startEndTimeWhere = startEndTimeWhere + " and type = '"+selectType+"' ";
				}
				  table.reload('contenttable',{
	                      method:'get',
	                      where:{
	                      	sendNumber:sendNumber
	                         //sendCompany:sendCompany
	  						,state:selectState
	  						,flag:selectFlag
	  						,startEndTimeWhere:startEndTimeWhere
	                      }
	                      ,page: {
	                      	//重新从第 1 页开始
	                          curr: 1
	                      }
	                  });
				
            },
	        reload:function () {
	            var materiel_name2 = $.trim($("#materiel_name2").val());
	            var materiel_num2 = $.trim($("#materiel_num2").val());
	          var verify = /^[0-9,-]*$/;
	    		//if(verify.test(materiel_num2)){ 
	    			var split = materiel_num2.split(',')
	    			if(split.length <= 5){
	    				table.reload('andProcut2Id',{
							method:'post'
							,where:{"materielName":materiel_name2,"materielNum":materiel_num2}
			         		,page: {
			                    curr: 1//重新从第 1 页开始
			                }
						});
	    			}else{
	    				layer.msg("最多可同时查5个！");
	    			}
	    	    /* }else{
	    			layer.msg("只能输入数字和英文逗号！");
	    		}  */
	        }
        }
        
      	//llm新增，添加物料的查询
        $(document).on('click','#selectMateriel',function(){
         	var materiel_name=$('#materiel_name').val();
     		var materiel_num=$('#materiel_num').val();
     		var table = layui.table;
     		var verify = /^[0-9,-]*$/;
    		//if(verify.test(materiel_num)){ 
    			var split = materiel_num.split(',')
    			if(split.length <= 5){
    				table.reload('productTable',{
						method:'post'
						,where:{"materielName":materiel_name,"materielNum":materiel_num}
		         		,page: {
		                    curr: 1//重新从第 1 页开始
		                }
					});
    			}else{
    				layer.msg("最多可同时查5个！");
    			}
    		 /* }else{
    			layer.msg("只能输入数字和英文逗号！");
    		}  */
    	}) 
    	
      	//点击行checkbox选中
	    $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
	        var index = $(this).attr('data-index');
	        var tableBox = $(this).parents('.layui-table-box');
	        //存在固定列
	        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
	            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
	        } else {
	            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
	        }
	        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
	        if (checkCell.length>0) {
	            checkCell.click();
	        }
	    });
	
	    $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
	        e.stopPropagation();
	    });
        
        $('.layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        var sendCompany = $.trim($("#sendCompany1").val());
        $("#selectState").val(0)
        form.render();
        table.render({
            elem: '#tableList'
            
            ,where:{state:0}
            ,url:'${pageContext.request.contextPath }/receive/list.do?sendCompany='+sendCompany
            ,title: 'machineList'
            ,id :'contenttable'
            ,limits:[10,20,30]
            ,toolbar: '#toolbar'
            ,cols: [
                [{type: 'checkbox',fixed: 'left'},
                    {field: 'id',title:'NO',sort: true,width: 50,type:'numbers',align:'center'},
                   // {field: 'receiveNumber',title: '收货单编号',align:'center'},
                    {field: 'sendNumber',title: '送货单编号',align:'center'},
                    {field: 'sendCompany',title: '供应商',align:'center',},
                    {field: 'sendName',title: '发货人',align:'center'},
                    {field: 'sendDate',title: '发货日期',align:'center'},
                    {field: 'receiveName',title: '收货人',align:'center'},
                    {field: 'receiveDate',title: '收货日期',align:'center',
                    	templet: function(d){
                    		return changeDateFormat(d.receiveDate)
                    }},
                    {field: 'confirmor',title: '确认人',align:'center'},
                    {field: 'confirmorDate',title: '确认日期',align:'center'
                    	,
                    	templet: function(d){
                    		return changeDateFormat(d.confirmorDate)
                    }},
                    {field: 'state',title: '状态',align:'center'
                        ,templet: function(d){
                            var value = d.state;
                            if(value == 0){
                                value = "未收货"
                            } else if (value == 1){
                                value = "已收货"
                            }
                            return value;
                        }
                    },
                    {
          	    	  	field:'imgLog',
          	    	  	title:'图片',
          	    	  	align:'center',
                        templet:function (d) {
                       	 	if(d.imgLog.length > 0){
                       		 	return '<div class="layer-photos-demo"><img src="'+d.imgLog+'" alt="" width="30px" height="30px"></a></div>';
                       	 	}else{
                       			return '无图片';
                       	 	}
                        }
          	      	},
                    {field: 'flag',title: '是否取消',align:'center' ,
                	templet: function(d){
                        var value = d.flag;
                        if(value == 0){
                        	value= '<a class="" style="color:red">已取消</a>';
                        }else if(value == 1){
                            value = "已恢复"
                        }else if(value == 2){
                            value = "未操作"
                        }
                        return value;
                    }},
                    /* {field: 'cancellation',title: '取消人',align:'center'},
                    {field: 'cancellation_time',title: '取消时间',align:'center'
                    	,
                    	templet: function(d){
                    		return changeDateFormat(d.cancellation_time)
                    }},
                    {field: 'restorer',title: '恢复人',align:'center'},
                    {field: 'restorer_time',title: '恢复时间',align:'center'
                    	,
                    	templet: function(d){
                    		return changeDateFormat(d.restorer_time)
                    }}, */
                    {field: 'remark',title: '备注',align:'center'},
                    {fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar', width:100, align: 'center'}
                ]
            ]
            ,page: true
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold'
                });
              	//调用示例
                layer.photos({//点击图片弹出
                    photos: '.layer-photos-demo'
                    ,anim: 1 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                	,area: ['800px','600px']
                });
            }
        });
      
		
        /* 打印单据 */
        table.render({
            elem: '#dytable'
            //,url:'${pageContext.request.contextPath }/receiveDetail/list.do'
            ,title: '明细表'
            ,cols: [[
                 {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                 {field:'materiel_num', title:'QAD/SAP', align:'center', width: 250},
                 /* {field:'brevity_num', title:'供应商零件号', align:'center', width: 200}, */
                 {field:'materiel_name', title:'中文描述', align:'center', width: 350,},
                 {field:'unit', title:'单位', align:'center', width: 87},
                 {field:'packing_quantity', title:'单包装数', width: 100, align:'center'},
                 {field:'sendNum', title:'发货包装数', align:'center', width: 100},
                 {field:'totalNum', title:'发货件数', align:'center', width: 100},
                 {field:'receiveNum', title:'实收包装数', align:'center', width: 100,
	                    templet: function (row){
	                    	var value = 0;
	                    	if(null != row.packing_quantity && row.codeNum != 0){
	                    		value = Math.ceil(row.codeNum/row.packing_quantity);
                            }
                            return value;
                        },
                 },
                 {field:'codeNum', title:'实收件数', align:'center', width: 100},
                 {field:'pici', title:'批号/备注', align:'center', width: 150},
             ]]
            ,page: false
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });
        /* 打印标签 */
        table.render({
            elem: '#bqtable'
            ,title: '条码表'
            ,cols: [[
				 {type: 'checkbox',fixed: 'left'},
                 {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                 {field:'SAP_QAD', title:'SAP_QAD', align:'center', width: 150},
                 {field:'materiel_name', title:'中文名称', align:'center', width: 200
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.receiveDetail	!= null){
	                    	 value = d.receiveDetail.materiel_name
	                     }
	                     return value;
                 	}
                 },
                 /* {field:'brevity_num', title:'零件号', align:'center', width: 200
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.receiveDetail	!= null){
	                    	 value = d.receiveDetail.brevity_num
	                     }
	                     return value;
                 	}
                 }, */
                 {field:'packing_quantity', title:'包装数量', width: 100, align:'center'
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.receiveDetail	!= null){
	                    	 value = d.receiveDetail.packing_quantity
	                     }
	                     return value;
                 	}
                 },
                 {field:'pici', title:'批次', align:'center'
                	 ,templet: function(d){
	                     var value = "";
	                     if(d.receiveDetail	!= null){
	                    	 value = d.receiveDetail.pici
	                     }
	                     return value;
                 	}
                 },
                 {field:'code', title:'条码', align:'center', width: 200},
                 {field:'num', title:'数量', align:'center', width: 150,},
             ]]
            ,page: false
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });
        
        /*=======================点击收货计划的下表=======================*/
        table.on('row(tableList)', function(obj){
        	var data = obj.data;
        	$("#getReceiveNumberValue").val(data.receiveNumber);
        	$("#gys").val(obj.data.sendCompany);
        	$("#subDiv").show();
            customerId2 = data.customerId;
            receiveNumber2 = data.receiveNumber;
            table.render({
                elem: '#tableDetails'
                ,url:'${pageContext.request.contextPath }/receiveDetail/list.do?receiveNumber='+data.receiveNumber
                ,toolbar: '#toolbar'
                ,title: '明细表'
                ,id :'contenttableDetails'
                ,limits:[10,20,30]
                //,defaultToolbar:['filter', 'print']
                ,cols: [[
                    {type: 'checkbox',fixed: 'left'},
                    {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                    {field:'mid', title:'物料id', align:'center', hide:true},
                    {field:'materiel_num', title:'SAP/QAD', align:'center', 
                    	event: 'collapse',
						templet: function(d) {
							return '<div style="position: relative;'+'padding: 0 10px 0 20px;">' + d.materiel_num + '<i style="left: 0px;" lay-tips="展开" class="layui-icon layui-colla-icon layui-icon-right"></i></div>'
						}
                    },
                    {field:'materiel_name', title:'中文名称', align:'center', width: 200,
						/*event: 'collapse',
						templet: function(d) {
							return '<div style="position: relative;'+'padding: 0 10px 0 20px;">' + d.materiel_name + '<i style="left: 0px;" lay-tips="展开" class="layui-icon layui-colla-icon layui-icon-right"></i></div>'
						}*/
                    },
                    //{field:'customer_name', title:'供应商名称', align:'center'},
                    //{field:'brevity_num', title:'零件号', align:'center'},
                    //{field:'materiel_size', title:'物料规格', align:'center'},
                    //{field:'materiel_properties', title:'物料型号', align:'center'},
                    //{field:'unit', title:'单位', align:'center', width: 100},
                    {field:'packing_quantity', title:'包装数量', width: 100, align:'center'},
                    //{field:'container_name', title:'容器名称', align:'center'},
                    {field:'is_devanning', title:'是否拆箱', align:'center'
                        ,templet: function(d){
                            var value = d.is_devanning;
                            if(value == 0){
                                return "是";
                            } else if (value == 1) {
                                return "否";
                            }
                        }
                    },
                    //{field:'devanning_num', title:'拆箱数', align:'center'},
                    //{field:'outgoing_frequency', title:'出库频率', align:'center'},
                    {
                        field: 'barcode_type',
                        title: '条码类型',
                        align:'center',
                        templet: function(d){
                            var value = d.barcode_type;
                            if(value == 0){
                                return "精准码";
                            } else if (value == 1) {
                                return "产品码";
                            } else {
                                return "简码";
                            }
                        }
                    },
                    {field:'pici', title:'批次', align:'center'},
                    {field:'sendNum', title:'发货箱数(箱)', align:'center', width: 110},
                    {field:'singleNum', title:'发货单数(个)', align:'center', width: 110},
                    {field:'totalNum', title:'发货总数(个)', align:'center', width: 110
                    	/* templet: function(d){
	                        if (d.barcode_type == 0) {
	                            if (d.singleNum > 0) {
	                                return ((d.sendNum - 1) * d.packing_quantity) + d.singleNum;
	                            } else {
	                                return d.sendNum * d.packing_quantity;
	                            }
							} else {
	                            return d.sendNum * d.packing_quantity + d.singleNum;
							} 
						}*/
                    },
                    //{field:'receiveNum', title:'收货箱数(箱)', align:'center', width: 110},
                    //{field:'single_num', title:'收货单数(个)', align:'center', width: 110},
                    {field:'codeNum', title:'收货总数(个)', align:'center', width: 110},
                    //{field:'rcode', title:'二维码', align:'center', templet:'<div><img style="height:100%; width: 50px"; src="http://localhost:8000/rcode/receive_rcode/{{ d.rcode }}"></div>'}
                ]]
                ,page: true
                ,done : function(){
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                }
            });
        });
       
        table.render({
            elem: '#productAddTable'
            ,defaultToolbar:['filter', 'print']
            ,cols: [[
                {type: 'checkbox',fixed: 'left'},
                {field:'id', title:'序号', width: 50,type:'numbers', align:'center'},
                {field:'id', title:'id', align:'center', hide:true},
                {field:'mid', title:'mid', align:'center', hide:true},
                //{field:'customer_name', title:'供应商名称', align:'center',width:100},
                {field:'materiel_num', title:'SAP/QAD', align:'center'},
                {field:'materiel_name', title:'中文名称', align:'center', width:150},
                /* {field:'brevity_num', title:'零件号', align:'center'}, */
                //{field:'unit', title:'单位', align:'center',width:60},
                {field:'packing_quantity', title:'包装数量', align:'center', width: 90},
                /* {field:'container_name', title:'容器名称', align:'center'},
                {field:'is_devanning', title:'是否拆箱', align:'center',width:80
                    ,templet: function(d){
                        var value = d.is_devanning;
                        if(value == '0'){
                            return "是";
                        } else if (value == '1') {
                            return "否";
                        }
                    }
                }, 
                {field:'devanning_num', title:'拆箱数', align:'center',width:70},
                {field:'outgoing_frequency', title:'出库频率', align:'center', width: 90},
                {
                    field: 'barcode_type',
                    title: '条码类型',
                    align:'center',
                    width: 90
                    ,templet: function(d){
                        var value = d.barcode_type;
                        if(value == 0){
                            return "精准码";
                        } else if (value == 1) {
                            return "产品码";
                        } else {
                            return "简码";
                        }
                    }
                },*/
                {field:'pici', title:'<span style="color: red">批次</span>', edit: 'text', align:'center'},
                {field:'sendNum', title:'<span style="color: red">发货数量(箱)</span>', edit: 'text', align:'center', width: 110},
                {field:'singleNum', title:'<span style="color: red">单个数量(个)</span>', edit: 'text', align:'center', width: 110},
                {field:'receiveNum', unresize: true, title:'发货总数', align:'center', templet: function(d){
                	 var sum=0;
                	 if(d.singleNum!= 0){
                            sum = (parseInt(d.sendNum) * parseInt(d.packing_quantity) + parseInt(d.singleNum));
                            return sum;
                        } else if (d.sendNum!= 0){
                            sum = (parseInt(d.sendNum) * parseInt(d.packing_quantity));
                            return sum;
                        } else {
                                return 0;
                        }
                     }
                },
                //{field:'singleNum', title:'<span style="color: red">数量(个)</span>', edit: 'text', align:'center', width: 110},
                //{field:'receiveNum', title:'收货数量', align:'center'},
                //{fixed: 'right',title:'<a onclick="addProduct()"><i class="layui-icon layui-icon-search" style="font-size: 13px; color: #1E9FFF;"></i>查找带回</a>',toolbar: '#productAddRowToolbar',align:'center',unresize: true,width:125}
            	//{fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar2',width:100, align: 'center'}
            ]]
            ,limit:Number.MAX_VALUE
            ,page: false
            ,height: 400
            ,done : function(){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });

        //监听行工具事件
        table.on('tool(productAddTable)', function(obj){
            var data = obj.data;
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            //单个删除
            if(obj.event === 'delete1'){
                layer.confirm('确定删除吗？', function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                });
            }
        });
        
        //监听收货计划管理的编辑事件
        table.on('tool(tableList)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                if(data.state != 0){
                    toastr.warning("对不起，已收货的数据不能修改！");
                    return;
                }
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['1100px', '640px'] 	//宽  高
                    ,title: '编辑'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content: $('#addDivID')
                    ,end: function () {
                        var formDiv = document.getElementById('addDivID');
                        formDiv.style.display = '';
                    }
                    ,success: function(){
                        $("#id").val(data.id)
                        $("#receiveNumber").val(data.receiveNumber)
                        $("#sendNumber").val(data.sendNumber)
                        $("#sendCompany").val(data.sendCompany)
                        $("#sendName").val(data.sendName)
                        $("#sendDate").val(data.sendDate)
                        var newData = new Array();
                        $.ajax({
                            type:'post',
                            data:'receiveNumber='+data.receiveNumber,
                            url:'${pageContext.request.contextPath}/receiveDetail/queryAllByMution.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (data) {
                                newData = data;
                            }
                        });
                        table.reload('productAddTable',{
                            data : newData
                        });
                        form.render();
                    }
                });
            } else if (obj.event === 'confirmor'){
            	var num = 0;
                $.ajax({
                    type:'post',
                    data:'receiveNumber='+data.receiveNumber,
                    url:'${pageContext.request.contextPath}/receiveDetail/queryAllByMution.do',
                    dataType: 'JSON',
                    async: false,
                    success:function (data) {
                    	for (var i = 0; i < data.length; i++) {
	                    	num = num + data[i].codeNum;
						}
                    }
                });
                //alert(num)
                if(num > 0){
	            	$.ajax({
	                    type:'post',
	                    data:'id='+data.id,
	                    url:'${pageContext.request.contextPath}/receive/updateStatus.do',
	                    dataType: 'JSON',
	                    async: false,
	                    success:function (data) {
	                        if(data > 0){
	                        	toastr.success('操作成功');
	                        }else{
	                        	toastr.error('操作失败');
	                        }
	                        setTimeout(function(){
	                            window.location.reload();
	                        },1000);
	                    }
	                });
                }else{
                	toastr.warning("对不起，收货数量为0的数据不能确认收货！");
                	return;
                }
            }
        });
    
        //监听收货计划管理详细表的父子表事件
        table.on('tool(tableDetails)', function(obj){
			if (obj.event === 'collapse') {
				var trObj = layui.$(this).parent('tr'); //当前行
				var accordion = true //开启手风琴，那么在进行折叠操作时，始终只会展现当前展开的表格。
				var content = '<table></table>' //内容
				//表格行折叠方法
				collapseTable({
					elem: trObj,
					accordion: accordion,
					content: content,
					success: function (trObjChildren, index) { //成功回调函数
						//trObjChildren 展开tr层DOM
						//index 当前层索引
						trObjChildren.find('table').attr("id", index);
                        /*===================================start===================================*/
						table.render({
							elem: "#" + index
                            ,url:'${pageContext.request.contextPath }/receiveDetail/queryReceiveMarkByReceiveId.do?receiveDetailId=' + obj.data.id
                            ,title: 'machineList'
                            //,limits:[10,20,30]
                            ,cols:
								[[
                                    {field:'id', title:'序号', sort: true, width: 60, type:'numbers', align:'center'},
                                    {field:'SAP_QAD',title: 'SAP_QAD',align:'center',},
                                    {field:'num', title: '数量', align:'center'},
                                    {field:'code', title: '条码', align:'center'},
                                ]]
                            ,page: false
                            /*,done : function(){
                                $('th').css({
                                    'background-color': '#009688', 'color': '#fff','font-weight':'bold'
                                })
                            }*/
						});
						/*===================================end===================================*/
					}
				});
			}
        });

        //选择供应商选中id查询该供应商的所有物料
        form.on('select(sendCompany)', function(data){
            var customer_id = data.value;
            $.ajax({
                type:'post',
                data:'id='+customer_id,
                url:'${pageContext.request.contextPath}/others/customerByName.do',
                dataType: 'JSON',
                async: false,
                success:function (json) {
                    if(null != json){
                        $("#sendName").val(json.contacts_name)
                    }
                }
            });
            table.reload('productAddTable',{
                data : new Array()
            });
        });

        /**
         * 添加弹框中，选择物料后，点提交，带回的操作
         */
        form.on('submit(productform)', function (data) {
            var flag;
            var oldData = table.cache["productAddTable"];
            var checkStatus = table.checkStatus('productTable')
            //选中的物料
            var data = checkStatus.data;
            for (var j = 0; j < data.length; j++) {
                for (var k = 0; k < oldData.length; k++) {
                    if (oldData[k].id == data[j].id) {
                        flag = 0;
                    }
                }
            }
            if (flag != 0) {
                for (var i = 0; i < data.length; i++) {
                    oldData.push(data[i]);
                }
            } else {
                toastr.warning("记录已经存在，不能重复添加");
            }
            table.reload('productAddTable',{
                data : oldData
            });
            $('[lay-id="productAddTable"] [data-edit="text"]:first').click();
            layer.close(productIndex)
            return false;
        });

        /**
         * 新增--提交
         */
        form.on('submit(addForm)', function (data) {
            var receiveNumber = $("#receiveNumber").val();
            //获取明细中数据
            var oldData = table.cache["productAddTable"];
            var data = oldData.filter(function(item){
                var re = /^[0-9]\d*$/ ;
                //return item.sendNum == "" || item.sendNum == undefined || !re.test(item.sendNum) || item.pici == "" || item.pici == null || item.pici == undefined;
                return !re.test(item.pici) || item.pici == "" || !re.test(item.sendNum) || item.sendNum == "" ||  !re.test(item.singleNum) || item.singleNum == "";
            })
            if(oldData.length == 0){
                toastrStyle();
                toastr.warning("请添加物料详情！");
                return false;
            } else if (data.length > 0){
                toastrStyle();
                toastr.warning("请输入正确的批次号和发货量(大于0的正整数)");
            	return false;
            } else {
                //获取明细表中的所有记录，遍历，循环添加
                for (var i = 0; i < oldData.length; i++) {
                    var mid = oldData[i].id;
                    var sendNum = oldData[i].sendNum;
                    var receiveNum = oldData[i].receiveNum;
                    var pici = oldData[i].pici;
                    var singleNum = oldData[i].singleNum;
                    //添加收货明细
                    $.ajax({
                        url: '${pageContext.request.contextPath}/receiveDetail/insert.do' ,
                        type: 'post',
                        data: {receiveNumber:receiveNumber, mid:mid, sendNum:sendNum, receiveNum:receiveNum, pici:pici, singleNum:singleNum},
                        async: false,
                        dataType:'JSON',
                        success: function (result) {
                            if (result > 0) {
                                if(i == oldData.length - 1) {
                                    var title = "新增";
                                    var url = '${pageContext.request.contextPath}/receive/insert.do';
                                    var id = $.trim($("#id").val());
                                    if(id != "" && id != null && id != 'undefined'){
                                        var url = '${pageContext.request.contextPath}/receive/update.do';
                                        title = "修改";
                                    }

                                    //添加收货单
                                    $.ajax({
                                        url : url,
                                        data: $("#addFormID").serialize(),
                                        cache : false,
                                        async: false,
                                        type : "post",
                                    }).done(
                                        function(res) {
                                            if (res > 0) {
                                                toastr.success(title+'成功');
                                                setTimeout(function(){
                                                	layer.closeAll();
                                                	var sendNumber = $.trim($("#sendNumberc").val());
                                                    var sendCompany = $.trim($("#sendCompanyc").val());
                                                    var selectState = $.trim($("#selectState").val());
                                                    var selectFlag=$('#selectFlag').val();
                                                    var startEndTimeWhere = "";
                                                    var startTime = $.trim($("#startTime").val());
                                                    if(selectState==''){
                                                    	
                                                    	selectState=0;
                                                    }
                                    				if(startTime != null && startTime != ""){
                                    					startEndTimeWhere = startEndTimeWhere + " and send_date >= '"+startTime+"' ";
                                    				}
                                    				var endTime = $.trim($("#endTime").val());
                                    				if(endTime != null && endTime != ""){
                                    					startEndTimeWhere = startEndTimeWhere + " and send_date <= '"+endTime+"' ";
                                    				}
                                    				  table.reload('contenttable',{
                                    	                      method:'get',
                                    	                      where:{
                                    	                      	sendNumber:sendNumber
                                    	                         //sendCompany:sendCompany
                                    	  						,state:selectState
                                    	  						,flag:selectFlag
                                    	  						,startEndTimeWhere:startEndTimeWhere
                                    	                      }
                                    	                      ,page: {
                                    	                      	//重新从第 1 页开始
                                    	                          curr: 1
                                    	                      }
                                    	                  });
                                                },1000);
                                            }
                                        }
                                    ).fail(
                                        function(res) {
                                            toastr.error(title+'失败！');
                                            setTimeout(function(){
                                            	layer.closeAll();
                                            	var sendNumber = $.trim($("#sendNumberc").val());
                                                var sendCompany = $.trim($("#sendCompanyc").val());
                                                var selectState = $.trim($("#selectState").val());
                                                var selectFlag=$('#selectFlag').val();
                                                var startEndTimeWhere = "";
                                                var startTime = $.trim($("#startTime").val());
                                                if(selectState==''){
                                                	
                                                	selectState=0;
                                                }
                                				if(startTime != null && startTime != ""){
                                					startEndTimeWhere = startEndTimeWhere + " and send_date >= '"+startTime+"' ";
                                				}
                                				var endTime = $.trim($("#endTime").val());
                                				if(endTime != null && endTime != ""){
                                					startEndTimeWhere = startEndTimeWhere + " and send_date <= '"+endTime+"' ";
                                				}
                                				  table.reload('contenttable',{
                                	                      method:'get',
                                	                      where:{
                                	                      	sendNumber:sendNumber
                                	                         //sendCompany:sendCompany
                                	  						,state:selectState
                                	  						,flag:selectFlag
                                	  						,startEndTimeWhere:startEndTimeWhere
                                	                      }
                                	                      ,page: {
                                	                      	//重新从第 1 页开始
                                	                          curr: 1
                                	                      }
                                	                  });
                                            },1000);
                                        }
                                    )
                                }

                            }else{
                                toastr.warning("对不起，请添加明细！");
                            }
                        },
                        error: function (data) {
                        	toastr.warning("对不起，请添加明细！");
                        }
                    })
                }
                return false;
            }
        });

        /**
         * 下表添加物料提交
         */
        form.on('submit(productform2)', function (data) {
        	//获取收货单号
        	var receiveNumber = $("#getReceiveNumberValue").val();
        	//获取该表格中选中的数据
        	var checkStatus = table.checkStatus('andProcut2Id')
        	var checkData = checkStatus.data;
        	//获取明细中数据
            //var oldData = table.cache["andProcut2Id"];
        	//alert(checkData.length);
            var data = checkData.filter(function(item){
                var re = /^[0-9]\d*$/ ;
                return !re.test(item.pici) || item.pici == "" || !re.test(item.sendNum) || item.sendNum == "" ||  !re.test(item.singleNum) || item.singleNum == "";
            })
            if(checkData.length == 0){
                toastrStyle();
                toastr.warning("请添加物料详情！");
                return false;
            } /* else if (checkData.length > 0){
                toastrStyle();
                toastr.warning("请输入正确的批次号和发货量(大于0的正整数)");
            	return false;
            } */ else {
	        	for (var i = 0; i < checkData.length; i++) {
	        		//checkData[i].id指的是物料id
					var mid = checkData[i].id;
					var sendNum = checkData[i].sendNum;
		            var receiveNum = checkData[i].receiveNum;
		            var pici = checkData[i].pici;
		            var singleNum = checkData[i].singleNum;
		            //添加收货明细
		            $.ajax({
		                url: '${pageContext.request.contextPath}/receiveDetail/insertReceiveDetail.do' ,
		                type: 'post',
		                data: {receiveNumber:receiveNumber, mid:mid, sendNum:sendNum, receiveNum:receiveNum, pici:pici, singleNum:singleNum},
		                async: false,
		                dataType:'JSON',
		                success: function (result) {
		                    if (result > 0) {
		                    	toastr.success("新增成功！");
		                    	setTimeout(function(){
		                    		layer.closeAll();

		                    		 table.reload('contenttableDetails',{
              	                      method:'get',
              	                     
              	                     page: {
              	                      	//重新从第 1 页开始
              	                          curr: 1
              	                      }
		                    		 })
	                            },1000);
		                    } else if (result == 0) {
		                    	toastr.warning("该物料已存在，请选择其他物料");
		                    	/* setTimeout(function(){
	                                window.location.reload();
	                            },1000); */
		                    } else {
		                        toastr.warning("对不起，明细添加失败！");
		                    }
		                },
		                error: function (data) {
		                	toastr.warning("对不起，请添加明细！");
		                }
		            })
				}
            }
        });
        
      	/* ======收货单的批次行内编辑====== */
        /* table.on('edit(productAddTable)', function(obj){
            var fieldValue = obj.value, 	//得到修改后的值
            rowData = obj.data.pici, 		//得到所在行所有键值
            fieldName = obj.field; 			//得到字段
            //保存修改出库单详细表的值    
            alert(rowData);
            layui.use('jquery',function() {
                var $ = layui.$;
                $.ajax({
                    type: "post",
                    url: "${pageContext.request.contextPath}/stockOutOrder/updateOutStockOrderDetailById.do",
                    data: {id:rowData.id, fieldName:fieldName, fieldValue:fieldValue },
                    success: function(zcInventoryInfoId){
                        if(zcInventoryInfoId > 0) {
                            toastrStyle();
                            toastr.success("修改成功！");
                        }else{
                            toastrStyle();
                            toastr.warning("修改失败！");
                        }
                    }
                });
            });
        }); */
        
        $("#export").click(function(){
       	 var sendNumber = $.trim($("#sendNumberc").val());
         var sendCompany = $.trim($("#sendCompanyc").val());
            var selectState = $.trim($("#selectState").val());
            
            var startEndTimeWhere = "";
            var startTime = $.trim($("#startTime").val());
				if(startTime != null && startTime != ""){
					startEndTimeWhere = startEndTimeWhere + " and send_date >= '"+startTime+"' ";
				}
				var endTime = $.trim($("#endTime").val());
				if(endTime != null && endTime != ""){
					startEndTimeWhere = startEndTimeWhere + " and send_date <= '"+endTime+"' ";
				}
         
           window.location.href="${pageContext.request.contextPath}/receive/doExportall.do?sendNumber="+sendNumber+"&sendCompany="+sendCompany
           +"&state="+selectState +"&startEndTimeWhere="+startEndTimeWhere;
       })
      	/* ============ */
        //增加
        $("#add").click(function(){
            layer.open({
                type: 1 					//Page层类型
                ,area: ['1100px', ''] 		//宽  高
                ,title: '新增'
                ,shade: 0.6 				//遮罩透明度
                ,maxmin: true 				//允许全屏最小化
                ,anim: 1 					//0-6的动画形式，-1不开启
                ,content: $('#addDivID')
                ,end: function () {
                    var formDiv = document.getElementById('addDivID');
                    formDiv.style.display = '';
                    $("#sendName").val("");
                    $("#sendNumber").val("");
                }
                ,success: function(){
                    var timestamp = (new Date()).getTime();
                    $("#receiveNumber").val("R-"+timestamp);

                    laydate.render({
                        elem: '#sendDate'
                        	 ,type: 'datetime'
                    });

                    $("#sendDate").val(curentTime())
                    table.reload('productAddTable',{
                        data : new Array()
                    });

                    $("#sendCompany").val("")
                    form.render();
                }
            });
        });
        
        //llm 监听行内编辑
        table.on('edit(productAddTable)', function(obj){
        	  var oldData = table.cache["productAddTable"];
        	 table.reload('productAddTable',{
                 data : oldData
             }); 
        	//设置jQuery对象
        	LayUIDataTable.SetJqueryObj($);
        	//隐藏列-单列模式
            LayUIDataTable.HideField('num');
         	//隐藏列-多列模式
            LayUIDataTable.HideField(['num','match_guest']);
            var currentRowDataList = LayUIDataTable.ParseDataTable(function (index, currentData, rowData) {
            	$("#getIndex").val(index);
            })
            /* ========================== */
        	var fieldValue = obj.value, //改变后的值
	    	 	rowData = obj.data, 	//得到所在行所有键值
             	fieldName = obj.field; 	//得到字段
           	var sum = 0;
          	//如果发货数量有值
            if(rowData.sendNum.length != 0){
            	//如果单个数量也有值
           		if(rowData.singleNum.length != 0){
           			sum = (parseInt(rowData.sendNum) * parseInt(rowData.packing_quantity) + parseInt(rowData.singleNum))
           		} else {
           			sum = (parseInt(rowData.sendNum) * parseInt(rowData.packing_quantity));
           		}
           	}
            var opt = rowData.receiveNum;
            opt = sum;
            var allTr = $("#addFormID").find(".layui-table tbody").eq(0).find("tr");
            
           	for(var i = 0; i < allTr.length; i++){
				if($("#getIndex").val() == i){
                    var oldData = table.cache["productAddTable"];
                    table.reload('productAddTable',{
                        data : oldData
                    });
					allTr.eq(i).children("td").eq(11).children('div').html(opt);
           		}
          	}
        });
	    	
        //监听下表新增物料的行内编辑事件
        table.on('edit(productTable2)', function(obj){
        	//设置jQuery对象
        	LayUIDataTable.SetJqueryObj($);
        	//隐藏列-单列模式
            LayUIDataTable.HideField('num');
         	//隐藏列-多列模式
            LayUIDataTable.HideField(['num','match_guest']);
            var currentRowDataList = LayUIDataTable.ParseDataTable(function (index, currentData, rowData) {
            	$("#getIndex").val(index);
            })
            /* ========================== */
        	var fieldValue = obj.value, //改变后的值
	    	 	rowData = obj.data, 	//得到所在行所有键值
             	fieldName = obj.field; 	//得到字段
           	var sum = 0;
            //如果发货数量有值
            if(rowData.sendNum.length != 0){
            	//如果单个数量也有值
           		if(rowData.singleNum.length != 0){
           			sum = (parseInt(rowData.sendNum) * parseInt(rowData.packing_quantity) + parseInt(rowData.singleNum))
           		} else {
           			sum = (parseInt(rowData.sendNum) * parseInt(rowData.packing_quantity));
           		}
           	}
            var opt = rowData.receiveNum;
            opt = sum;
            var allTr = $("#addFormID2").find(".layui-table-main tbody").eq(0).find("tr");
          	for(var i = 0; i < allTr.length; i++){
				if($("#getIndex").val() == i){
					allTr.eq(i).children("td").eq(10).children('div').html(opt);
          		}
         	}
        });
        
        //收货计划单批量删除
        $("#dels").click(function() {
       
            var checkStatus = table.checkStatus('contenttable')
            var data = checkStatus.data;
            var idArr = new Array();
            if(data.length == 0){
                toastr.warning("请至少选择一条记录！");
            }else{
                var ids = "";
                for(var i=0;i<data.length;i++){
                    if(data[i].state != 0){
                        toastr.warning("对不起，已收货的数据不能取消！");
                        return;
                    }
                    if(data[i].receiveName != "" && data[i].receiveName != undefined && data[i].receiveName != null ){
                        toastr.warning("对不起，已收货的数据不能取消！");
                        return;
                    }
                    if(data[i].flag == 0){
                        toastr.warning("对不起，已取消的数据不能取消！");
                        return;
                    }
                    if(i == 0 || i == "0"){
                        ids += data[i].id
                    }else{
                        ids += "," + data[i].id;
                    }
                }
                layer.confirm('确定取消吗？', function(index){
                    $.ajax({
                        type:'post',
                        url:'${pageContext.request.contextPath }/receive/delete.do',
                        data:{"ids":ids},
                        success:function(data){
                            if(data > 0){
                                toastr.success("取消成功！");
                                setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                    //关闭模态框
                                    //父页面刷新
                                	layer.closeAll();
                                	var sendNumber = $.trim($("#sendNumberc").val());
                                    var sendCompany = $.trim($("#sendCompanyc").val());
                                    var selectState = $.trim($("#selectState").val());
                                    var selectFlag=$('#selectFlag').val();
                                    var startEndTimeWhere = "";
                                    var startTime = $.trim($("#startTime").val());
                                    if(selectState==''){
                                    	
                                    	selectState=0;
                                    }
                    				if(startTime != null && startTime != ""){
                    					startEndTimeWhere = startEndTimeWhere + " and send_date >= '"+startTime+"' ";
                    				}
                    				var endTime = $.trim($("#endTime").val());
                    				if(endTime != null && endTime != ""){
                    					startEndTimeWhere = startEndTimeWhere + " and send_date <= '"+endTime+"' ";
                    				}
                    				  table.reload('contenttable',{
                    	                      method:'get',
                    	                      where:{
                    	                      	sendNumber:sendNumber
                    	                         //sendCompany:sendCompany
                    	  						,state:selectState
                    	  						,flag:selectFlag
                    	  						,startEndTimeWhere:startEndTimeWhere
                    	                      }
                    	                      ,page: {
                    	                      	//重新从第 1 页开始
                    	                          curr: 1
                    	                      }
                    	                  });
                                },2000);
                            } else {
                                toastr.warning("取消失败！");
                            }
                        }

                    })
                    layer.closeAll();
                });
            }
        
            
       });
        $("#restors").click(function() {
        	
            var checkStatus = table.checkStatus('contenttable')
            var data = checkStatus.data;
            var idArr = new Array();
            if(data.length == 0){
                toastr.warning("请至少选择一条记录！");
            }else{
                var ids = "";
                for(var i=0;i<data.length;i++){
                    if(data[i].state != 0){
                        toastr.warning("对不起，已收货的数据不能恢复！");
                        return;
                    } if(data[i].flag == 1){
                        toastr.warning("对不起，已恢复的数据不能恢复！");
                        return;
                    }
                    if(i == 0 || i == "0"){
                        ids += data[i].id
                    }else{
                        ids += "," + data[i].id;
                    }
                }
                layer.confirm('确定恢复吗？', function(index){
                    $.ajax({
                        type:'post',
                        url:'${pageContext.request.contextPath }/receive/restor.do',
                        data:{"ids":ids},
                        success:function(data){
                            if(data > 0){
                                toastr.success("恢复成功！");
                                setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                    //关闭模态框
                                    //父页面刷新
                                	layer.closeAll();
                                	var sendNumber = $.trim($("#sendNumberc").val());
                                    var sendCompany = $.trim($("#sendCompanyc").val());
                                    var selectState = $.trim($("#selectState").val());
                                    var selectFlag=$('#selectFlag').val();
                                    var startEndTimeWhere = "";
                                    var startTime = $.trim($("#startTime").val());
                                    if(selectState==''){
                                    	
                                    	selectState=0;
                                    }
                    				if(startTime != null && startTime != ""){
                    					startEndTimeWhere = startEndTimeWhere + " and send_date >= '"+startTime+"' ";
                    				}
                    				var endTime = $.trim($("#endTime").val());
                    				if(endTime != null && endTime != ""){
                    					startEndTimeWhere = startEndTimeWhere + " and send_date <= '"+endTime+"' ";
                    				}
                    				  table.reload('contenttable',{
                    	                      method:'get',
                    	                      where:{
                    	                      	sendNumber:sendNumber
                    	                         //sendCompany:sendCompany
                    	  						,state:selectState
                    	  						,flag:selectFlag
                    	  						,startEndTimeWhere:startEndTimeWhere
                    	                      }
                    	                      ,page: {
                    	                      	//重新从第 1 页开始
                    	                          curr: 1
                    	                      }
                    	                  });
                                },2000);
                            } else {
                                toastr.warning("恢复失败！");
                            }
                        }

                    })
                    layer.closeAll();
                });
            }
     
     });
        
      	//单据合并
        $("#merge").click(function() {
        	
            var checkStatus = table.checkStatus('contenttable')
            var data = checkStatus.data;
            var idArr = new Array();
            if(data.length < 2){
                toastr.warning("请至少选择两条记录！");
            }else{
                var ids = "";
                var customerName = data[0].sendCompany;
                for(var i=0;i<data.length;i++){
                    if(data[i].state != 0){
                        toastr.warning("对不起，已收货的数据不能合并！");
                        return;
                    }
                    if(data[i].flag == 0){
                        toastr.warning("对不起，已取消的数据不能合并！");
                        return;
                    }
                    if(data[i].sendCompany != customerName){
                    	toastr.warning("对不起，只能合并相同供应商的单据！");
                        return;
                    }
                    if(i == 0 || i == "0"){
                        ids += data[i].id
                    }else{
                        ids += "," + data[i].id;
                    }
                }
                var timestamp = (new Date()).getTime();
                var receiveNumber = "R-"+timestamp;
                layer.confirm('确定合并吗？', function(index){
                    $.ajax({
                        type:'post',
                        url:'${pageContext.request.contextPath }/receive/merge.do',
                        data:{"ids":ids, "receiveNumber":receiveNumber},
                        success:function(data){
                            if(data > 0){
                                toastr.success("合并成功！");
                                setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                	var sendNumber = $.trim($("#sendNumberc").val());
                                    var sendCompany = $.trim($("#sendCompanyc").val());
                                    var selectState = $.trim($("#selectState").val());
                                    var selectFlag=$('#selectFlag').val();
                                    var startEndTimeWhere = "";
                                    var startTime = $.trim($("#startTime").val());
                                    if(selectState==''){
                                    	
                                    	selectState=0;
                                    }
                    				if(startTime != null && startTime != ""){
                    					startEndTimeWhere = startEndTimeWhere + " and send_date >= '"+startTime+"' ";
                    				}
                    				var endTime = $.trim($("#endTime").val());
                    				if(endTime != null && endTime != ""){
                    					startEndTimeWhere = startEndTimeWhere + " and send_date <= '"+endTime+"' ";
                    				}
                    				  table.reload('contenttable',{
                    	                      method:'get',
                    	                      where:{
                    	                      	sendNumber:sendNumber
                    	                         //sendCompany:sendCompany
                    	  						,state:selectState
                    	  						,flag:selectFlag
                    	  						,startEndTimeWhere:startEndTimeWhere
                    	                      }
                    	                      ,page: {
                    	                      	//重新从第 1 页开始
                    	                          curr: 1
                    	                      }
                    	                  });
                     				
                                },2000);
                            } else {
                                toastr.warning("合并失败！");
                            }
                        }
                    })
                    layer.closeAll();
                });
            }
        
         });
        
        //llm 收货单详情添加物料
        $("#addProduct").click(function() {
      
        	var checkStatus = table.checkStatus('contenttable')
            var data = checkStatus.data;
        	var str = "";
        	if(data.length == 0){
                toastr.warning("请选择一条记录！");
            } else if(data.length > 1){
            	toastr.warning("只能选择一条记录！");
            }else if(data[0].flag== 0){
            	toastr.warning("对不起，已取消的数据不能添加物料！");
            }else{
            	for(var i = 0; i < data.length; i++){
            		if(data[i].state != "0"){
            			toastr.warning("对不起，已收货的数据不能添加物料！");
            			return;
            		}
            	}
            	layer.open({
            		type: 1 					//Page层类型
                    ,area: ['900px', '700px'] 	//宽  高
                    ,title: '物料清单'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content: $('#productDiv2')
                    ,end: function () {
                        var formDiv = document.getElementById('productDiv2');
                        formDiv.style.display = '';
                        $("#materiel_num2").val("")
                    }
                    ,success: function(){
                    	table.render({
                            elem: '#productTable2'
                            ,id:'andProcut2Id'
                            //,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?id='+customer_id
                            //,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?customer_id='+customer_id
                            ,url:'${pageContext.request.contextPath}/cancellingStockDetailManager/listPageMaterielByCustomerIdAndWarehouseId.do?customerId='+customerId2+'&source=1'
                            ,limit:10000
                            ,defaultToolbar:['filter', 'print']
                          
                            ,cols: [
                                [{
                                    type: 'checkbox',
                                    fixed: 'left'
                                }, {
                                    field:'id2',
                                    title:'序号',
                                    sort: true,
                                    width: 60,
                                    type:'numbers',
                                    align:'center'
                                }, {
                                    field: 'id',
                                    title: 'id',
                                    hide: true
                                } , {
                                    field: 'materiel_num',
                                    title: 'SAP/QAD',
                                    align:'center',
                                /* }, {
    	                            field: 'brevity_num',
    	                            title: '零件号',
    	                            align:'center', */
                            	}, {
                                    field: 'materiel_name',
                                    title: '中文名称',
                                    align:'center',
                                }, {
                                    field: 'packing_quantity',
                                    title: '包装数量',
                                    align:'center',
                                }, {
                                    field: 'pici',
                                    title: '批次',
                                    align:'center',
                                    edit:true,
                                }, {
                                    field: 'sendNum',
                                    title: '发货数量（箱）',
                                    align:'center',
                                    edit:true,
                                }, {
                                    field: 'singleNum',
                                    title: '单个数量(个)',
                                    align:'center',
                                    edit:true,
                                }, {
                                	field:'receiveNum', 
                                	title:'发货总数(个)', 
                                	align:'center', 
                                	width: 110
                                }]
                            ]
                            ,page: false
                        });
                    }
            	});
            }
       
        });
        
    	//收货计划单详细批量删除
        $("#delete2").click(function() {
      
        	var checkStatusParent = table.checkStatus('contenttable')
            var dataParent = checkStatusParent.data;
            var checkStatus = table.checkStatus('contenttableDetails')
            var data = checkStatus.data;
            var idArr = new Array();
            if(data.length == 0){
                toastr.warning("请至少选择一条记录！");
            } else {
                var ids = "";
                for(var i = 0; i < data.length; i++) {
                   /*  if(dataParent[i].state != 0){
                        toastr.warning("对不起，已收货的数据不能删除！");
                        return;
                    } */
                    if(data[i].codeNum > 0){
                    	toastr.warning("对不起，已收货的数据不能删除！");
                        return;
                    }
                    if(i == 0 || i == "0"){
                        ids += data[i].id
                    } else {
                        ids += "," + data[i].id;
                    }
                }
                layer.confirm('确定删除吗？', function(index){
                    $.ajax({
                        type : 'post',
                        url : '${pageContext.request.contextPath }/receiveDetail/delete.do',
                        data : {"ids":ids},
                        success : function(data){
                            if(data > 0) {
                                toastr.success("删除成功！");
                                setTimeout(function(){
                                	 table.reload('contenttableDetails',{
                 	                      method:'get',
                 	                     
                 	                     page: {
                 	                      	//重新从第 1 页开始
                 	                          curr: 1
                 	                      }
                 	                  });
                                	},2000);
                            } else {
                                toastr.warning("删除失败！");
                            }
                        }

                    })
                    layer.closeAll();
                });
            }
       
        });
      
      	//打印表单
        $("#dybd").click(function(){
        	var checkStatus = table.checkStatus('contenttable')
            var datas = checkStatus.data;
            if(datas.length!=1){
                toastr.warning("请选择一条记录！");
            }else{
            	var data = datas[0]
	            layer.open({
	                type: 1 					//Page层类型
	                ,area: ['1450px', '650px'] 			//宽  高
	                ,title: '打印表单'
	                ,shade: 0.6 				//遮罩透明度
	                ,maxmin: true 				//允许全屏最小化
	                ,anim: 1 					//0-6的动画形式，-1不开启
	                ,content: $('#dybdDivID')
	                ,end: function () {
	                    var formDiv = document.getElementById('dybdDivID');
	                    formDiv.style.display = '';
	                }
	                ,success: function(){
	                	//alert(data.sendPhone + "== "+ data.sendAdress);
                        $("#sendNumbers").html(data.sendNumber);
                        $("#createDate").html(data.sendDate);
                        $("#sendNames").html(data.sendCompany);
                        $("#sendPeoples").html(data.sendName);
                        $("#sendPhones").html(data.sendPhone);
                        //$("#receiveNames").html(data.receiveName);
                        $("#sendAddress").html(data.sendAdress);
                        //二维码路径
                        var path = '${pageContext.request.contextPath}/'
                        $.ajax({
                            type:'post',
                            data:'code='+data.receiveNumber,
                            url:'${pageContext.request.contextPath}/label/erWeiMa.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (data) {
                            	path = path+data.path;
                            }
                        });
                        $("#bd_img").attr("src",path)
                        
                        var newData = new Array();
                        $.ajax({
                            type:'post',
                            data:'receiveNumber='+data.receiveNumber,
                            url:'${pageContext.request.contextPath}/receiveDetail/queryAllByMution.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (data) {
                                console.log(data);
                            	newData = data;
                            }
                        });
                        table.reload('dytable',{
                            data : newData
                            ,limit:newData.length
                        });
	                }
	            });
            }
        });
      	
        $("#dayingTable").click(function(){
			//var innerHTML = document.getElementById("dyDiv").innerHTML;
        	//printpage(innerHTML)
		    var obj =document.getElementById('dyDiv')
			var css='<style>'
                //+"#dyTable td{border:1px solid #00000080;}"
                +'[lay-id="dytable"] table{border:1px solid #F00;border-collapse:collapse;}'
                +'[lay-id="dytable"] table td{border:1px solid #222;}'
                +'[lay-id="dytable"] table th{border:1px solid #222;font-size: 20px;}'
                +'[lay-id="dytable"] table th span{color: black;}'
                +'</style>'; 
			var newWindow=window.open("打印窗口","_blank");//打印窗口要换成页面的url
			var docStr =  css+ obj.innerHTML;
		    newWindow.document.write(docStr);
		    newWindow.document.close();
		    setTimeout(function () {
			    newWindow.print();
			    newWindow.close();
		    }, 100);
		});
      	//打印标签
        $("#dybq").click(function(){
        	var checkStatus = table.checkStatus('contenttable')
            var datas = checkStatus.data;
            if(datas.length!=1){
                toastr.warning("请选择一条记录！");
            }else{
            	var data = datas[0]
            	var tim=datas[0].sendDate
            	$('#dtim').val(tim)
	            layer.open({
	                type: 1 					//Page层类型
	                ,area: ['1210px', '600px'] 			//宽  高
	                ,title: '条码列表'
	                ,shade: 0.6 				//遮罩透明度
	                ,maxmin: true 				//允许全屏最小化
	                ,anim: 1 					//0-6的动画形式，-1不开启
	                ,content: $('#dybqDivID')
	                ,end: function () {
	                    var formDiv = document.getElementById('dybqDivID');
	                    formDiv.style.display = '';
	                }
	                ,success: function(){
                        var newData = new Array();
                        $.ajax({
                            type:'post',
                            data:'receiveId='+data.id,
                            url:'${pageContext.request.contextPath}/receiveDetail/selectReceiveMarkByReceiveId.do',
                            dataType: 'JSON',
                            async: false,
                            success:function (data) {
                                console.log(data);
                            	newData = data.data;
                            }
                        });
                        table.reload('bqtable',{
                            data : newData
                            ,limit:newData.length
                        });
	                }
	            });
            }
        });
      	//打印标签
        $("#dytm").click(function(){
        	var checkStatus = table.checkStatus('bqtable')
            var datas = checkStatus.data;
            if(datas.length < 1){
                toastr.warning("请选择条码！");
            }else{
            	layer.closeAll();
            	var num = datas.length;
           	  	var hight = '600px'
           	  	/* if(num > 2){
            	  	hight = '90%'
           	  	} */
           	  	var data = datas[0]
   	            layer.open({
   	                type: 1 					//Page层类型
   	                ,area: ['1200px', hight] 			//宽  高
   	                ,title: '打印标签'
   	                ,shade: 0.6 				//遮罩透明度
   	                ,maxmin: true 				//允许全屏最小化
   	                ,anim: 1 					//0-6的动画形式，-1不开启
   	                ,content: $('#dytmDivID')
   	                ,end: function () {
   	                    var formDiv = document.getElementById('dytmDivID');
   	                    formDiv.style.display = '';
   	                }
   	                ,success: function(){
   	                	var checkStatus = table.checkStatus('contenttable')
   	                 	var datas1 = checkStatus.data;
   	                	var customer_name = datas1[0].sendCompany;
   	                	
   	             	
   	                	var timem = $('#dtim').val();
   	                	var time=changeDateFormat(timem)
   	                	var tmwmimg = '<%=request.getContextPath()%>/';
   	                	var materiel_name = "";
   	                	var materiel_num = "";
   	                	var packing_quantity = "";
   	                	var pici = "";
   	                	var tm = "";
   	                	var tmnum = 0;
   	                	var tm2wmimg = "";
   	                	var tm1wmimg = "";
   	                	var code = datas;
  	                	var html = '';
  	                	
   	                	for (var i = 0; i < num; i++) {
                            //分页
                            if(i == 0){
	                            html += '<div class="A4">'
                            }else if(materiel_name != code[i].receiveDetail.materiel_name){
		                            html += '</div>'
		                            html += '<div class="A4">'
                            /* }else{
	                            if(i%6 == 0){
		                            html += '</div>'
		                            html += '<div class="A4">'
	                            } */
                            }
                            
   	                		/* tm = code[i][0];
                            tm2wmimg = tmwmimg+code[i][1];
                            tm1wmimg = tmwmimg+code[i][2]; */
                            var receiveDetail = code[i].receiveDetail
                            materiel_name = receiveDetail.materiel_name;
       	                	materiel_num = receiveDetail.materiel_num;
       	                	packing_quantity = receiveDetail.packing_quantity;
       	                	pici = receiveDetail.pici;
       	                	
   	                		tm = code[i].code;
                            tmnum = code[i].num;
                            tm2wmimg = tmwmimg+code[i].twoCodePath;
                            tm1wmimg = tmwmimg+code[i].barCodePath;
                            
                            
   	                		html += '<table class="tmdyTable" style="border: 2px solid #222;width: 540px;height: 260px;margin:0 auto;margin-bottom: 20px;display:inline-table;/*display:inline-block; float:left;*/ margin-left: 48px;">'
   	                			html += '<tr>'
   	                				html += '<td width="100" align="center">'
   	                					html += '零件名称：'
   	                				html += '</td>'
   	                				html += '<td width="220">'
   	                				html += materiel_name
   	                				html += '</td>'
   	                				html += '<td rowspan="8" width="200">'
   	                					html += '<img src="'+tm2wmimg+'" width="100%" height="100%"/>'
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += 'SAP/QAD：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += materiel_num
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '供应商：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += customer_name
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '包装信息：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += packing_quantity
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '包装数量：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += tmnum
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '日期时间：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += time
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '批次信息：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += pici
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td align="center">'
   	                					html += '条码信息：'
   	                				html += '</td>'
   	                				html += '<td>'
   	                					html += tm
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr>'
   	                				html += '<td colspan="3">'
   	                					html += '<img src="'+tm1wmimg+'" width="100%" height="50px" id="dpddremark_dy"/>'
   	                				html += '</td>'
   	                			html += '</tr>'
   	                			html += '<tr style="height:5px"></tr>'
   	                		html += '</table>'
						}
   	                	//分页
   	                	html += '</div>'
   	                	var tmdyDiv = document.getElementById("tmdyDiv");
  	                		tmdyDiv.innerHTML= html;
   	                }
   	            });
            }
        });
        $("#dayingTmdyTable").click(function(){
        	//layer.closeAll();
		    var obj =document.getElementById('tmdyDiv')
			var newWindow=window.open("打印窗口","_blank");//打印窗口要换成页面的url
			var css='<style>'
				+".A4 {page-break-before: auto;page-break-after: always;}"
                +".tmdyTable td{border:1px solid #00000080;}"
                +'.tmdyTable{border:1px solid #F00;border-collapse:collapse;}'
                +'.tmdyTable td{border:1px solid #222;}'
                +'</style>'; 
			var docStr =  css+ obj.innerHTML;
			newWindow.document.write(docStr);
		    newWindow.document.close();
		    newWindow.print();
		    //newWindow.close(); 
            /* cc =  docStr;
	        var isIe=0;
	        if(navigator.userAgent.indexOf('MSIE')>0){
	          isIe = 1;
	        }
	        var frame = document.getElementById('dsh_myframe');
	        if (!frame) {
	          if (isIe) {
	            frame = document.createElement('<iframe id = "dsh_myframe"></iframe>');
	          } else {
	            frame = document.createElement('iframe');
	            frame.id ='dsh_myframe';
	            frame.setAttribute('style','width: 0pt; height: 0pt;')
	          }
	        }
	        if (isIe) {
	          frame.src = 'javascript:;';
	          frame.style.cssText= 'width: 0pt; height: 0pt;';
	        }
	        document.body.appendChild(frame);
	        if (isIe) {
	          doc = frame.contentWindow.document;
	        } else {
	          doc = frame.contentDocument;
	        }
	        doc.write(cc);
	        doc.close();
	        frame.contentWindow.focus();
	        if(isIe){
	          setTimeout(function(){
	            frame.contentWindow.print();
	          },2);
	        }else{
	          frame.contentWindow.print();
	        }  */
	        
		});
        function changeDateFormat(timestamp) {
        	if (timestamp == '') {
    			return '';
    		} else {
    			var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    			Y = date.getFullYear() + '-';
    			M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    			D = (date.getDate()+1 < 10 ? '0'+(date.getDate()) : date.getDate())+ '      ';
    			H = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours())+ ':';
                MI= (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes())+':';
                S = (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
    				
    				
    				return Y+M+D+H+MI+S;
    		
    		}
        }
		//表格行折叠方法
        function collapseTable(options) {
            var trObj = options.elem;
            if (!trObj) {
                return;
            }
            var accordion = options.accordion,
                success = options.success,
                content = options.content || '';
            var tableView = trObj.parents('.layui-table-view'); //当前表格视图
            var id = tableView.attr('lay-id'); //当前表格标识
            var index = trObj.data('index'); //当前行索引
            var leftTr = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + index + '"]'); //左侧当前固定行
            var rightTr = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + index + '"]'); //右侧当前固定行
            var colspan = trObj.find('td').length; //获取合并长度
            var trObjChildren = trObj.next(); //展开行Dom
            var indexChildren = id + '-' + index + '-children'; //展开行索引
            var leftTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-l tr[data-index="' + indexChildren + '"]'); //左侧展开固定行
            var rightTrChildren = tableView.find('.layui-table-fixed.layui-table-fixed-r tr[data-index="' + indexChildren + '"]'); //右侧展开固定行
            var lw = leftTr.width() + 15; //左宽
            var rw = rightTr.width() + 15; //右宽
            //不存在就创建展开行
            if (trObjChildren.data('index') != indexChildren) {
                //装载HTML元素
                var tr = '<tr data-index="' + indexChildren + '"><td colspan="' + colspan + '"><div style="height: auto;padding-left:' + lw + 'px;padding-right:' + rw + 'px" class="layui-table-cell">' + content + '</div></td></tr>';
                trObjChildren = trObj.after(tr).next().hide(); //隐藏展开行
                var fixTr = '<tr data-index="' + indexChildren + '"></tr>';//固定行
                leftTrChildren = leftTr.after(fixTr).next().hide(); //左固定
                rightTrChildren = rightTr.after(fixTr).next().hide(); //右固定
            }
            //展开|折叠箭头图标
            trObj.find('td[lay-event="collapse"] i.layui-colla-icon').toggleClass("layui-icon-right layui-icon-down");
            //显示|隐藏展开行
            trObjChildren.toggle();
            //开启手风琴折叠和折叠箭头
            if (accordion) {
                trObj.siblings().find('td[lay-event="collapse"] i.layui-colla-icon').removeClass("layui-icon-down").addClass("layui-icon-right");
                trObjChildren.siblings('[data-index$="-children"]').hide(); //展开
                rightTrChildren.siblings('[data-index$="-children"]').hide(); //左固定
                leftTrChildren.siblings('[data-index$="-children"]').hide(); //右固定
            }
            success(trObjChildren, indexChildren); //回调函数
            heightChildren = trObjChildren.height(); //展开高度固定
            rightTrChildren.height(heightChildren + 115).toggle(); //左固定
            leftTrChildren.height(heightChildren + 115).toggle(); //右固定
        }
    });

    /*================点击选择物料的弹框================*/
    function addProduct (){
        if($("#sendNumber").val().trim() == ""){
			layer.msg("请输入送货单号！");
		} else {
            productIndex = layer.open({
                type: 1 					//Page层类型
                ,area: ['900px', '700px'] 	//宽  高
                ,title: '物料清单'
                ,shade: 0.6 				//遮罩透明度
                ,maxmin: true 				//允许全屏最小化
                ,anim: 1 					//0-6的动画形式，-1不开启
                ,content: $('#productDiv')
                ,end: function () {
                    var formDiv = document.getElementById('productDiv');
                    formDiv.style.display = '';
                    $("#materiel_num").val("")
                }
                ,success: function () {
                    var customer_id = $("#sendCompany1").val();
                    table.render({
                        elem: '#productTable'
                        //,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?id='+customer_id
                        //,url:'${pageContext.request.contextPath }/receiveDetail/materielList.do?customer_id='+customer_id
                        ,url:'${pageContext.request.contextPath}/cancellingStockDetailManager/listPageMaterielByCustomerIdAndWarehouseId.do?customerId='+customer_id+'&source=1'
                        ,limit:10000
                        ,defaultToolbar:['filter', 'print']
                        
                        ,cols: [
                            [{
                                type: 'checkbox',
                                fixed: 'left'
                            }, {
                                field:'id',
                                title:'序号',
                                sort: true,
                                width: 60,
                                type:'numbers',
                                align:'center'
                            }, {
                                field: 'id',
                                title: 'id',
                                hide:true
                            } /* , {
                                field: 'customer_name',
                                title: '供应商名称',
                                align:'center',
                            } */, {
                                field: 'materiel_num',
                                title: 'SAP/QAD',
                                align:'center',
                            /* }, {
	                            field: 'brevity_num',
	                            title: '零件号',
	                            align:'center', */
                        	}, {
                                field: 'materiel_name',
                                title: '中文名称',
                                align:'center',
                            },/*  {
                                field: 'outgoing_frequency',
                                title: '出库频率',
                                align:'center',
                            }, */ {
                                field: 'packing_quantity',
                                title: '包装数量',
                                align:'center',
                            } 
                            ]
                        ]
                        ,page: false
                    });
                }
            });
		}
    }

    //获取当前时间
    function curentTime() {
    	  var now=new Date();
          var year=now.getFullYear(); 
  	     var month=now.getMonth()+1; 
  	     var date=now.getDate(); 
  	     var hour=now.getHours(); 
  	     var minute=now.getMinutes(); 
  	     var second=now.getSeconds(); 
  	     if (month >= 1 && month <= 9) {
  	        month = "0" + month;
  	    }
  	    if (date >= 0 && date <= 9) {
  	       date = "0" + date;
  	    } 
  	   if (hour >= 1 && hour <= 9) {
  		  hour = "0" + hour;
  	    }
  	  if (minute >= 1 && minute <= 9) {
  		 minute = "0" + minute;
  	    }
  	 if (second >= 1 && second <= 9) {
  		second = "0" + second;
  	    }
  	var time =year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 

         return time;
    }
    
    function add0(m){
        return m<10?'0'+m:m
    }
    
    toastrStyle();
    //获取行索引
    var LayUIDataTable = (function () {
        var rowData = {};
        var $;
        function checkJquery () {
            if (!$) {
                console.log("未获取jquery对象，请检查是否在调用ConvertDataTable方法之前调用SetJqueryObj进行设置！")
                return false;
            } else return true;
        }
        function ConvertDataTable (callback) {
            if (!checkJquery()) return;
            var dataList = [];
            var rowData = {};
            var trArr = $(".layui-table-body.layui-table-main tr");// 行数据
            if (!trArr || trArr.length == 0) {
                console.log("未获取到相关行数据，请检查数据表格是否渲染完毕！");
                return;
            }
            $.each(trArr, function (index, trObj) {
                var currentClickRowIndex;
                var currentClickCellValue;

                $(trObj).click(function (e) {
                    var returnData = {};
                    var currentClickRow = $(e.currentTarget);
                    currentClickRowIndex = currentClickRow.data("index");
                    currentClickCellValue = e.target.innerHTML
                    $.each(dataList[currentClickRowIndex], function (key, obj) {
                        returnData[key] = obj.value;
                    });
                    callback(currentClickRowIndex, currentClickCellValue, returnData);
                });
                var tdArrObj = $(trObj).find('td');
                rowData = {};
                //  每行的单元格数据
                $.each(tdArrObj, function (index_1, tdObj) {
                    var td_field = $(tdObj).data("field");
                    rowData[td_field] = {};
                    rowData[td_field]["value"] = $($(tdObj).html()).html();
                    rowData[td_field]["cell"] = $(tdObj);
                    rowData[td_field]["row"] = $(trObj);

                })
                dataList.push(rowData);
            })
            return dataList;
        }

        return {
            SetJqueryObj: function (jqueryObj) {
                $ = jqueryObj;
            }
            , ParseDataTable: ConvertDataTable
            , HideField: function (fieldName) {
                if (!checkJquery()) return;
                if (fieldName instanceof Array) {
                    $.each(fieldName, function (index, field) {
                        $("[data-field='" + field + "']").css('display', 'none');
                    })
                } else if (typeof fieldName === 'string') {
                    $("[data-field='" + fieldName + "']").css('display', 'none');
                } else {

                }
            }
        }
    })();
</script>
</body>
</html>
